import inquirer from 'inquirer';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import chalk from 'chalk';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export async function createProject(projectName) {
    // 如果没有提供项目名，通过交互式命令获取
    if (!projectName) {
        const answers = await inquirer.prompt([
            {
                type: 'input',
                name: 'projectName',
                message: '请输入项目名称:',
                validate: (input) => {
                    if (!input || input.trim() === '') {
                        return '项目名称不能为空';
                    }
                    return true;
                }
            }
        ]);
        
        projectName = answers.projectName;
    }

    const targetPath = path.resolve(projectName);

    // 检查目录是否已存在
    if (fs.existsSync(targetPath)) {
        const { overwrite } = await inquirer.prompt({
            type: 'confirm',
            name: 'overwrite',
            message: `目录 ${projectName} 已存在，是否覆盖？`,
            default: false
        });
        
        if (!overwrite) {
            console.log(chalk.yellow('项目创建已取消'));
            return;
        }
        
        // 删除已有目录
        fs.removeSync(targetPath);
    }

    try {
        // 添加项目配置选项
        const answers = await inquirer.prompt([
            {
                type: 'input',
                name: 'description',
                message: '请输入项目描述:',
                default: '基于Vue 3的项目'
            },
            {
                type: 'list',
                name: 'jsType',
                message: '请选择JavaScript类型:',
                choices: [
                    { name: 'JavaScript', value: 'js' },
                    { name: 'TypeScript', value: 'ts' }
                ],
                default: 'js'
            },
            {
                type: 'list',
                name: 'framework',
                message: '请选择前端框架:',
                choices: [
                    { name: 'Vue 3', value: 'vue' },
                    { name: 'React', value: 'react' }
                ],
                default: 'vue'
            },
            {
                type: 'list',
                name: 'template',
                message: '请选择项目模板:',
                choices: [
                    { name: '默认模板', value: 'default' }
                ],
                default: 'default'
            }
        ]);

        console.log(chalk.cyan('正在创建项目...'));
        
        // 复制模板文件
        const templatePath = path.join(__dirname, `../templates/${answers.template}`);
        fs.copySync(templatePath, targetPath);

        // 更新新项目的package.json
        const packageJsonPath = path.join(targetPath, 'package.json');
        const packageJson = await fs.readJson(packageJsonPath);
        packageJson.name = projectName;
        packageJson.description = answers.description;
        packageJson.version = '1.0.0';
        
        // 根据用户选择更新依赖
        if (answers.jsType === 'ts') {
            console.log(chalk.cyan('配置TypeScript环境...'));
            packageJson.devDependencies = {
                ...packageJson.devDependencies,
                "typescript": "^5.0.0",
                "@types/node": "^20.0.0"
            };
            
            if (answers.framework === 'vue') {
                packageJson.devDependencies["@vue/tsconfig"] = "^0.5.0";
            } else if (answers.framework === 'react') {
                packageJson.devDependencies["@types/react"] = "^18.0.0";
                packageJson.devDependencies["@types/react-dom"] = "^18.0.0";
            }
        }
        
        // 根据框架选择更新依赖
        if (answers.framework === 'react') {
            console.log(chalk.cyan('配置React环境...'));
            packageJson.dependencies = {
                ...packageJson.dependencies,
                "react": "^18.0.0",
                "react-dom": "^18.0.0",
                "react-router-dom": "^6.0.0"
            };
            delete packageJson.dependencies.vue;
            delete packageJson.dependencies["vue-router"];
            
            // 更新开发依赖
            if (packageJson.devDependencies["@vitejs/plugin-vue"]) {
                delete packageJson.devDependencies["@vitejs/plugin-vue"];
                packageJson.devDependencies["@vitejs/plugin-react"] = "^4.0.0";
            }
        }
        
        await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });

        // 根据JavaScript类型创建配置文件
        if (answers.jsType === 'ts') {
            // 创建tsconfig.json
            const tsconfigPath = path.join(targetPath, 'tsconfig.json');
            const tsconfig = {
                "compilerOptions": {
                    "target": "ES2020",
                    "useDefineForClassFields": true,
                    "module": "ESNext",
                    "lib": ["ES2020", "DOM", "DOM.Iterable"],
                    "skipLibCheck": true,
                    "moduleResolution": "bundler",
                    "allowImportingTsExtensions": true,
                    "resolveJsonModule": true,
                    "isolatedModules": true,
                    "noEmit": true,
                    "strict": true,
                    "noUnusedLocals": true,
                    "noUnusedParameters": true,
                    "noFallthroughCasesInSwitch": true
                },
                "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
                "references": [{ "path": "./tsconfig.node.json" }]
            };
            
            // 根据框架调整tsconfig
            if (answers.framework === 'vue') {
                tsconfig.compilerOptions.jsx = "preserve";
            } else if (answers.framework === 'react') {
                tsconfig.compilerOptions.jsx = "react-jsx";
            }
            
            await fs.writeJson(tsconfigPath, tsconfig, { spaces: 2 });
            
            // 创建tsconfig.node.json
            const tsconfigNodePath = path.join(targetPath, 'tsconfig.node.json');
            const tsconfigNode = {
                "compilerOptions": {
                    "composite": true,
                    "skipLibCheck": true,
                    "module": "ESNext",
                    "moduleResolution": "bundler",
                    "allowSyntheticDefaultImports": true
                },
                "include": ["vite.config.ts"]
            };
            await fs.writeJson(tsconfigNodePath, tsconfigNode, { spaces: 2 });
        }
        
        // 更新vite.config.js/ts以匹配所选框架
        const viteConfigExt = answers.jsType === 'ts' ? 'ts' : 'js';
        const viteConfigPath = path.join(targetPath, `vite.config.${viteConfigExt}`);
        
        if (fs.existsSync(viteConfigPath)) {
            let viteConfigContent = await fs.readFile(viteConfigPath, 'utf-8');
            
            if (answers.framework === 'react') {
                viteConfigContent = viteConfigContent
                    .replace(/@vitejs\/plugin-vue/g, '@vitejs/plugin-react')
                    .replace(/vue\(\)/g, 'react()');
            }
            
            await fs.writeFile(viteConfigPath, viteConfigContent, 'utf-8');
        }
        
        console.log(chalk.green('✅ 项目创建成功！'));
        console.log(chalk.blue('📦 下一步操作：'));
        console.log(`   cd ${projectName}`);
        console.log('   npm install');
        console.log('   npm run dev');
        
        // 显示项目配置信息
        console.log(chalk.yellow('\n📋 项目配置信息：'));
        console.log(`   项目名称: ${chalk.cyan(projectName)}`);
        console.log(`   项目描述: ${chalk.cyan(answers.description)}`);
        console.log(`   JavaScript类型: ${chalk.cyan(answers.jsType === 'js' ? 'JavaScript' : 'TypeScript')}`);
        console.log(`   前端框架: ${chalk.cyan(answers.framework === 'vue' ? 'Vue 3' : 'React')}`);
        console.log(`   项目模板: ${chalk.cyan(answers.template)}`);
        console.log(chalk.green('\n祝您开发愉快！🎉'));
    } catch (error) {
        console.error(chalk.red('创建项目失败：'), error.message);
    }
}